<?php
class Category extends Eloquent {
    protected $table = 'category';


    public function getCategories($id = null, $isRender = false, $value = false, $selectParentId = 0) {
        $categories = Category::all();

        if($isRender) {
            return $this->getRenderChildren($categories, $id, $value, $selectParentId);
        }else {
            return $this->getChildren($categories, $id);
        }
    }

    public function getChildren($array,$parent_id) {
        $temp_array = array();
        foreach($array as $element){
            if($element['p_id']==$parent_id){
                $element['subs'] = $this->getChildren($array,$element['id']);
                $temp_array[] = $element;
            }
        }
        return $temp_array;
    }




    function getRenderChildren($array, $parent_id, $value, $selectParentId, $i = 0, $menu_html = null){
        $i++;
        $textIndent = '';
        for($j = 1; $j < $i; $j++) {
            $textIndent .= ' - ';
        }

        foreach($array as $element){
            if($element['p_id']==$parent_id){
                $isSelected = "";
                if($value && !$selectParentId) {
                    $isSelected = $element['id'] == $value?'selected="selected"': '';
                }
                if($selectParentId) {
                    $isSelected = $element['id'] == $selectParentId?'selected="selected"': '';
                }
                $menu_html .= '<option value="'. $element['id'] .'" '. $isSelected .'>'. $textIndent .$element['name'] .'</option>';
                $menu_html .= $this->getRenderChildren($array, $element['id'], $value, $selectParentId, $i);
            }
        }
        return $menu_html;
    }


}

